﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.TeamFoundation.Build.Client;
using System.Diagnostics;
using System.IO;

namespace TeamDeploy.Activities
{
    [BuildActivity(HostEnvironmentOption.Agent)]
    public sealed class WebDeploy : CustomActivityBase
    {
        [RequiredArgument]
        public InArgument<string> DeploymentPackageSharePathCmd { get; set; }
        
        [RequiredArgument]
        public InArgument<string> TargetMachine { get; set; }

        public InArgument<string> Username { get; set; }

        public InArgument<string> Password { get; set; }

        public InArgument<string> AllowUntrusted { get; set; }

        public InArgument<string> UseBasicAuthentication { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            string deploymentPackageSharePathCmd = context.GetValue(this.DeploymentPackageSharePathCmd);
            string targetMachine = context.GetValue(this.TargetMachine);
            bool ignoreExitCode = false;
            bool.TryParse(context.GetValue(this.IgnoreExitCode), out ignoreExitCode);
            string username = context.GetValue(this.Username) + "";
            string password = context.GetValue(this.Password) + "";
            bool allowUntrusted = false;
            bool.TryParse(context.GetValue(this.AllowUntrusted), out allowUntrusted);
            bool useBasicAuthentication = false;
            bool.TryParse(context.GetValue(this.UseBasicAuthentication), out useBasicAuthentication);

            string usernameArg = username.Length > 0 ? " /u:" + username : "";
            string passwordArg = password.Length > 0 ? " /p:" + password : "";
            string useBasicAuthenticationArg = useBasicAuthentication ? " /A:basic" : "";
            string allowUntrustedArg = allowUntrusted ? " -allowUntrusted" : "";


            // Publishing Endpoint
            string publishingEndPointOption;
            if (targetMachine.ToUpper() == System.Environment.MachineName)
            {
                publishingEndPointOption = "";
            }
            else
            {
                publishingEndPointOption = "/M:https://" + targetMachine + ":8172/MsDeploy.axd";
            }

            using (System.Diagnostics.Process process = new System.Diagnostics.Process())
            {
                process.StartInfo.FileName = deploymentPackageSharePathCmd;
                //process.StartInfo.WorkingDirectory = SearchPathRoot.Get(context);                    
                process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.ErrorDialog = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.Arguments = "/y" + publishingEndPointOption + usernameArg + passwordArg + allowUntrustedArg + useBasicAuthenticationArg;

                try
                {
                    process.Start();
                    process.WaitForExit();
                    string output = process.StandardOutput.ReadToEnd();
                    
                    LogMessage(context, "WebDeploy Output:" + output);
                }
                catch (Exception ex)
                {
                    LogMessage(context, ex.ToString());
                    throw ex;
                }

                if (process.ExitCode != 0)
                {
                    string message = "Process WebDeploy" + " on " + targetMachine + " returned code:" + process.ExitCode;

                    if (ignoreExitCode)
                    {
                        LogMessage(context, message);
                    }
                    else
                    {
                        LogMessage(context, message);
                        //  return false;
                    }
                }
            }
        }
    }
}
